package org.mathcloud.math.core.scilab.operator;

import org.apache.log4j.Logger;
import org.mathcloud.math.core.generic.operator.GenericBinaryOperator;
import org.mathcloud.math.core.scilab.factory.ScilabQuantityObjectFactory;
import org.mathcloud.math.core.scilab.manager.ScilabSupervisor;
import org.mathcloud.math.core.scilab.quantity.ScilabQuantityObject;
import org.scilab.modules.javasci.JavasciException;
import org.scilab.modules.javasci.Scilab;
import org.scilab.modules.types.ScilabDouble;

public abstract class ScilabBinaryOperator extends GenericBinaryOperator
{
	public ScilabBinaryOperator()
	{
		super();
		sciEngine = ScilabSupervisor.getScilabEngine();
		signature.setRealizationName("scilab");
	}	

	public void calculate(String functionName, Logger log)
	{
		if (getResultSignature()!=null)
    {
      String sciJob;
      String tmpVar = "tmp_"+ScilabSupervisor.getVarId();
			ScilabQuantityObject tOp1 = ScilabQuantityObjectFactory.getInstance(operand1);
			ScilabQuantityObject tOp2 = ScilabQuantityObjectFactory.getInstance(operand2);
			sciJob = tmpVar;
			sciJob = sciJob + "="+functionName+"("+ tOp1.getVarName()+","+tOp2.getVarName()+");";
      if (sciEngine.exec(sciJob))
      {
      	log.info(sciJob);
      	try
				{
      		ScilabDouble tRes = (ScilabDouble)sciEngine.get(tmpVar);
	      	res = ScilabQuantityObjectFactory.getInstance(tRes);
					sciJob = "clear "+tmpVar+";";
					if (sciEngine.exec(sciJob))
						log.info(sciJob);					      	
				} catch (JavasciException e)
				{
					log.error(e);
				}
      }
      else
      {
      	res = null;
      	log.info(sciJob);
      	log.info(sciEngine.getLastErrorMessage());
      }
    }    		
	}	
	
	public Scilab getScilabEngine()
	{
		return sciEngine;
	}
	
	protected Scilab sciEngine;
}
